package com.tanhua.manager.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.tanhua.manager.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/system/users")
public class AdminController {
    @Autowired
    private AdminService adminService;

    /**
     * GET/system/users/verification
     * 验证码
     */
    @GetMapping("/verification")
    public void verification(String uuid, HttpServletResponse response) throws IOException {

        // 设置：禁止浏览器使用缓存
        response.setDateHeader("Expires", 0);
        //     Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        //     Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        //     Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // 设置：响应体内容是image/jpeg图片
        response.setContentType("image/jpeg");

        // 使用Hutools工具生成验证码图片
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(299, 97);

        // 获取验证码图片上的验证码真实值
        String code = captcha.getCode();

        // 把验证码真实值缓存起来
        adminService.cacheCode(code, uuid);

        // 把验证码图片响应给客户端
        captcha.write(response.getOutputStream());
    }

    /**
     * POST/system/users/login
     * 登录验证
     */
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map map){
        String username= (String) map.get("username");
        String password = (String) map.get("password");
        String code = (String) map.get("verificationCode");
        String uuid = (String) map.get("uuid");
        return adminService.login(username,password,code,uuid);
    }

    /**
     * POST/system/users/profile
     * 用户基本信息
     */
    @PostMapping("/profile")
    public ResponseEntity profile(){
        return adminService.profile();
    }

    /**
     * POST/system/users/logout
     * 退出登录
     */
    @PostMapping("/logout")
    public ResponseEntity logout(){
        return adminService.logout();
    }
}
